package com.itheima.reggie.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/dish/list")
    public ResultInfo findByCategoryId(Long categoryId,Integer status,String name) {
        String key = "dish_" + categoryId;
        List<Dish> dishList = (List<Dish>) redisTemplate.opsForValue().get(key);
        if (CollectionUtil.isNotEmpty(dishList)) {
            System.out.println("从Redis查询的");
            return ResultInfo.success(dishList);
        } else {

            System.out.println("从MySQL查询的");

            //查询不到, 就需要从MySQL中进行查询
            dishList = dishService.findByCategoryId(categoryId,name);

            //然后保存到Redis
            redisTemplate.opsForValue().set(key, dishList);

            // 再返回
            return ResultInfo.success(dishList);
        }
    }
}
